package com.gs.SynAntiWandering.activity.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.gs.SynAntiWandering.R;
import com.gs.SynAntiWandering.constant.EventCode;
import com.gs.SynAntiWandering.db.bean.Event;
import com.gs.SynAntiWandering.util.ActivityUtil;
import com.gs.SynAntiWandering.util.LanguageUtils;
import com.gs.SynAntiWandering.util.WindowUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

public abstract class BaseFragmentActivity extends FragmentActivity {
    private WeakReference<Activity> weakReference = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        EventBus.getDefault().register(this);
        if (weakReference == null) {
            weakReference = new WeakReference<Activity>(this);
        }
        ActivityUtil.getInstance().addActivity(weakReference.get());
        WindowUtil.setBarBgColor(this, R.color.green);
        initFragment();
        initView(savedInstanceState);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LanguageUtils.getInstance().change(LanguageUtils.getInstance().getCurLocale()));
    }

    protected abstract int getLayoutId();

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void initFragment();

    protected <I extends View> I fd(int id) {
        return findViewById(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityUtil.getInstance().removeActivity(weakReference.get());
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_LANGUAGE) {
            recreate();
        } else if (event.getWhat() == EventCode.EVENT_SITE) {
            recreate();
        }
    }
}
